import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import {
  generateRoutesByFrontEnd,
  generateRoutesByServer,
  flatMultiLevelRoutes
} from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import { getPermissionsApi } from '@/api/login'
import { useCrypto } from '@/hooks/web/useCrypto'
const { localEncrypt, localDecrypt } = useCrypto()

/**
 * 菜单约束
 */
interface MenuState {
  children: Array<object>
  component: any
  icon: string
  id: number
  keepAlive: boolean
  name: string
  parentId: number
  path: string
  visible: boolean
}
export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
  permissions: string[]
  roles: string[]
  rawMenus?: Array<MenuState>
  roleRouters?: string[] | AppCustomRouteRecordRaw[]
}

interface PermissionStateData {
  dept: object
  permissions: string[]
  roles: string[]
  user: object
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: [],
    permissions: [],
    roles: [],
    rawMenus: [],
    roleRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    },
    getPermissions(): string[] {
      return localDecrypt(this.permissions)
    },
    getRoleRouters(): string[] | AppCustomRouteRecordRaw[] | undefined {
      return localDecrypt(this.roleRouters)
    },
    getRoles(): string[] {
      return localDecrypt(this.roles)
    },
    getRawMenus(): Array<MenuState> | undefined {
      return localDecrypt(this.rawMenus)
    },
    getRawMenuTypes(): string[] | undefined {
      const arr = localDecrypt(this.rawMenus) || []
      return arr.map((item) => item.path)
    }
  },
  actions: {
    generateRoutes(
      type: 'server' | 'frontEnd' | 'static',
      routers?: AppCustomRouteRecordRaw[] | object[]
    ): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routerMap: AppRouteRecordRaw[] = []
        if (type === 'server') {
          // 模拟后端过滤菜单
          routerMap = generateRoutesByServer(routers as AppCustomRouteRecordRaw[])
        } else if (type === 'frontEnd') {
          // 模拟前端过滤菜单
          routerMap = generateRoutesByFrontEnd(
            cloneDeep(asyncRouterMap),
            routers as unknown as string[]
          )
        } else {
          // 直接读取静态路由表
          routerMap = cloneDeep(asyncRouterMap)
        }
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])
        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        resolve()
      })
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    },
    setPermissions(permissions: string[]): void {
      this.permissions = localEncrypt(permissions)
    },
    setRoleRouters(roleRouters: object[] | AppCustomRouteRecordRaw[]) {
      this.roleRouters = localEncrypt(roleRouters)
    },
    setRoles(roles: string[]): void {
      this.roles = localEncrypt(roles)
    },
    setRawMenus(rawMenus: Array<MenuState>) {
      this.rawMenus = localEncrypt(rawMenus)
    },
    /**
     * 获取权限
     */
    async getPermissionsInfo(): Promise<PermissionStateData> {
      return new Promise(async (resolve) => {
        await getPermissionsApi()
          .then((res) => {
            const { dept, permissions, roles, user } = res.data
            resolve({ dept, permissions, roles, user })
          })
          .catch(() => {})
      })
    },
    reset() {
      this.setPermissions([])
      this.setRoles([])
      this.setRawMenus([])
      this.setRoleRouters([])
    },
    logout() {
      this.reset()
    }
  },
  persist: {
    paths: [
      'routers',
      'addRouters',
      'menuTabRouters',
      'permissions',
      'roles',
      'rawMenus',
      'roleRouters'
    ]
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
